package dyyx;

import java.io.StringReader;
import org.codehaus.commons.compiler.IScriptEvaluator;
import org.codehaus.janino.ClassBodyEvaluator;
import org.codehaus.janino.ExpressionEvaluator;
import org.codehaus.janino.Scanner;
import org.codehaus.janino.ScriptEvaluator;

public class JaninoTest {

	public static void main(String[] args) throws Exception {
		String script="System.out.println(\"Hello world\");";
		IScriptEvaluator evaluator = new ScriptEvaluator();
		evaluator.cook(script);
		evaluator.evaluate(null);
		
	
		script = "(1+2)*3";
		evaluator = new ExpressionEvaluator();
		evaluator.cook(script);
		Object result = evaluator.evaluate(null);
		System.out.println(result + "=" + result+","+result.getClass());
		

		evaluator = new ExpressionEvaluator();
		script = "2 * (a + b)";
		evaluator.setParameters(new String[] { "a", "b" }, new Class[] { int.class, int.class }); 
	    // 表达式返回结果类型
		evaluator.setReturnType(int.class); 
		evaluator.cook(script); 
	    int intresult = (Integer) evaluator.evaluate(new Object[] { 1, 2 });
		System.out.println("intresult=" + intresult);
	
		
		script ="public int bar(int a, int b) { return a + b; }";
		Scanner scanner = new Scanner(null, new StringReader(script));
		Foo foo = (Foo)ClassBodyEvaluator.createFastClassBodyEvaluator(scanner,Foo.class,null);
		System.out.println(foo.bar(2, 3));
	}
	
	public interface Foo {
	    int bar(int a, int b);
	}
}
